package sign_in.loginsystem.service.realize;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sign_in.loginsystem.mapper.RoleAndPemMapper;
import sign_in.loginsystem.model.entity.Menu;
import sign_in.loginsystem.model.entity.Role;
import sign_in.loginsystem.model.util.PageBean;
import sign_in.loginsystem.model.util.RBody;
import sign_in.loginsystem.service.port.RoleImp;

import java.util.ArrayList;

@Service
public class RoleService implements RoleImp {

    @Resource
    RoleAndPemMapper roleMapper;

    @Override
    public PageBean allRole(RBody body) {
        PageBean pageBean = body.getPageBean();
        PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        ArrayList<Role> roles = roleMapper.allRole();
        for (Role role : roles) {
            ArrayList<Integer> integers = roleMapper.searchRolePemId(role);
            role.setMenus(roleMapper.searchRolePem(integers));
        }
        Page<Role> page = (Page<Role>) roles;
        pageBean.setAllPageNum((int) page.getTotal());
        pageBean.setRoles((ArrayList<Role>) page.getResult());
        pageBean.setAllObjectNum(roleMapper.roleNum());
        if(roleMapper.roleNum()%pageBean.getPageSize()!=0){
            pageBean.setAllPageNum(roleMapper.roleNum()/pageBean.getPageSize()+1);
        }
        else {
            pageBean.setAllPageNum(roleMapper.roleNum()/pageBean.getPageSize());
        }
        return pageBean;
    }

    @Transactional
    @Override
    public PageBean createRole(RBody body) {
        Role role=body.getRole();
        roleMapper.createRole(role);
        roleMapper.insertRoleAndMenu(role);
        return allRole(body);
    }

    @Override
    public PageBean editRole(RBody body) {
        System.out.println(body.getRole());
        roleMapper.editRole(body.getRole());
        return allRole(body);
    }

    @Override
    public PageBean delRole(RBody body) {
        roleMapper.delRole(body.getRole());
        return allRole(body);
    }



    @Override
    public ArrayList<Menu> allMenuRE() {
        return roleMapper.allMenu();
    }

    @Override
    public ArrayList<Role> roleRE() {
        return roleMapper.allRole();
    }



}
